package com.jxit0573.android.lib.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Base64;

import com.google.common.io.Files;

import org.zeroturnaround.zip.ZipUtil;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * @author jia
 */
public class FileUtils {

    private FileUtils() {
    }

    public static File getAppDirFile(Context context, String dirName) {
        File file = new File(Objects.requireNonNull(StringUtils.appends(Environment.getDataDirectory().getPath(), File.separator, context.getPackageName(), dirName)));
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }

    public static void writer(Context context, String dirName, String fileName, Object content, boolean append) {
        try {
            File file = new File(getAppDirFile(context, dirName), fileName);
            PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file, append)), true);
            pw.println(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void unpack(File parentFile, String zipPath, boolean isDelete) {
        File zipFile = new File(parentFile, zipPath);
        if (zipFile.exists()) {
            ZipUtil.unpack(zipFile, parentFile);
            if (isDelete) {
                zipFile.delete();
            }
        }
    }

    public static void handle(String fileName) {
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = reader.readLine()) != null) {

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String encode2Base64String(File file) {
        try {
            if (file == null || !file.exists()) {
                return null;
            } else {
                return Base64.encodeToString(Files.toByteArray(file), Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void bitmapToFile(Bitmap bitmap, File file) {
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
